<template>
  <div v-loading="loading" class="parentStyle">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('中介机构名称')" prop="mediationName">
            <el-autocomplete
              v-model="form.mediationName"
              class="inline-input name"
              :fetch-suggestions="companyQuerySearch"
              :placeholder="$t('公司全称')"
              :trigger-on-focus="false"
              :maxlength="100"
              show-word-limit
              @select="companyHandleSelect"
              @blur="checkNameExist(form.mediationName)"
            >
              <template v-if="enableTyc" slot="append">
                <a @click="companyHandleSelect">{{ $t('查询工商信息') }}</a>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('中介机构简称')" prop="mediationShortName">
            <el-input v-model="form.mediationShortName" :placeholder="$t('中介机构简称')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <!--        会计师事务所 律师事务所 资产评估机构 背景调查机构 业务咨询机构-->
        <el-col :span="12">
          <el-form-item :label="$t('中介机构类型')">
            <el-select v-model="form.mediationType" :placeholder="$t('中介机构类型')" multiple>
              <el-option
                v-for="dict in mediationTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <Area ref="cityZj" :buss-data="form" />
        <el-col :span="12">
          <el-form-item :label="$t('详细地址')" prop="detailsRegistered">
            <el-input v-model="form.detailsRegistered" :placeholder="$t('详细地址')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('企业统一社会信用代码')" prop="creditCode">
            <el-input v-model="form.creditCode" :placeholder="$t('企业统一社会信用代码')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('网址')" prop="site">
            <el-input v-model="form.site" :placeholder="$t('网址')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('职工人数')" prop="staff">
            <el-input v-model="form.staff" :placeholder="$t('职工人数')" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('电话')" prop="phone">
            <el-input v-model="form.phone" :placeholder="$t('电话')" show-word-limit maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('传真')" prop="fax">
            <el-input v-model="form.fax" :placeholder="$t('传真')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('法人代表')" prop="legalPerson">
            <el-input v-model="form.legalPerson" :placeholder="$t('法人代表')" show-word-limit maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('成立时间')" prop="establishTime">
            <DatePicker v-model="form.establishTime" :placeholder="$t('成立时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('注册资本') + $t('金额单位')" prop="registerCapital">
            <Money v-model="form.registerCapital" unit="w" :placeholder="$t('注册资本')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('注册资本币种')" prop="currency">
            <el-select v-model="form.currency" :placeholder="$t('注册资本币种')">
              <el-option
                v-for="(dict, index) in currencyOptions"
                :key="index"
                :value="dict.dictValue"
                :label="$t(dict.dictLabel)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('公司概况')" prop="companySurvey">
            <el-input v-model="form.companySurvey" type="textarea" :placeholder="$t('公司概况')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('公司亮点')" prop="companyHighlights">
            <el-input v-model="form.companyHighlights" type="textarea" :placeholder="$t('公司亮点')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 附件列表 -->
      <div style="margin-bottom: 10px;">
        <FileTable :list.sync="form.fileList" data-type="mediation_base" :btn-show="!otherBtnHide" />
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <SaveBtn has-permi="deal:mediation" :cancel-show="!this.$route.query.id" />
    </div>
  </div>
</template>

<script>
import { saveMediationBase, getMediationBase, getMediationBaseByName } from '@/api/deal/mediation/mediationBase'
import { Notification } from 'element-ui'
import { companyListByName, getCompanyByName } from '@/api/company/base/companyBase'
// 省市组件
import Area from '@/components/Area'
export default {
  components: {
    Area
  },
  data() {
    const numberCheck = (rule, value, callback) => {
      if (value !== undefined && value !== '' && value !== null) {
        // 校验电话
        if (rule.field === 'staff') {
          var regNumber = /^[0-9]*[0-9][0-9]*$/
          if (!regNumber.test(value)) {
            callback(new Error(this.$t('只能录入正整数')))
          }
          if (value.length > 10 || value > 2147483647) {
            callback(new Error(this.$t('数量过大')))
          }
        }
      }
      callback()
    }
    return {
      otherBtnHide: false,
      // 中介机构类型字典
      mediationTypeOptions: [], // 表单参数
      form: {},
      // 遮罩层
      loading: false,
      // 币种字典
      currencyOptions: [],
      // 表单校验
      rules: {
        mediationName: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        mediationShortName: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ],
        staff: [{ validator: numberCheck, trigger: 'blur' }]
      },
      // 天眼查查询条件
      tycParam: {
        id: '',
        companyName: '',
        tycId: '',
        orgType: ''
      },
      enableTyc: undefined
    }
  },
  created() {
    this.getDicts('intermediary_type').then(response => {
      this.mediationTypeOptions = response.data
    })
    this.getDicts('currency').then(response => {
      this.currencyOptions = response.data
    })
  },
  mounted() {
    this.$bus.$emit('async_done')
    this.enableTyc = (window.localStorage.getItem('enableTyc') === 'true')
  },
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      if (data != null && data.id !== undefined) {
        getMediationBase(data.id).then(response => {
          this.form = response.data
          this.$nextTick(() => {
            if (this.$refs?.cityZj?.initCity !== undefined) {
              this.$refs.cityZj.initCity()
              this.$refs.cityZj.initDistrict()
            }
          })
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        mediationName: undefined,
        mediationType: undefined,
        provinceRegistered: undefined,
        cityRegistered: undefined,
        detailsRegistered: undefined,
        districtRegistered: undefined,
        creditCode: undefined,
        site: undefined,
        staff: undefined,
        phone: undefined,
        fax: undefined,
        legalPerson: undefined,
        establishTime: undefined,
        registerCapital: undefined,
        currency: undefined,
        companySurvey: undefined,
        companyHighlights: undefined,
        remark: undefined,
        createBy: undefined,
        updateBy: undefined,
        createTime: undefined,
        updateTime: undefined,
        delFlag: undefined,
        tycId: undefined,
        logoInfo: undefined,
        companyId: undefined,
        mediationShortName: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm(form) {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      this.$parent.$parent.formOpen = false
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
      if (this.$parent.$parent.processingDataEcho !== undefined) {
        const data = {
          id: form.id,
          mediationName: form.mediationName,
          mediationShortName: form.mediationShortName
        }
        this.$parent.$parent.processingDataEcho(data, 'mediationBaseForm')
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form']
        .validate(valid => {
          if (valid) {
            this.loading = true
            saveMediationBase(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('保存成功'))
                this.closeForm(response.data)
              } else {
                this.msgError(response.msg)
                this.loading = false
              }
            })
          } else {
            this.locationError(document)
          }
        })
        .cancel(() => {
          this.loading = false
        })
    },
    // 标的公司查询
    companyQuerySearch(queryString, cb) {
      // 录入一个空格报错问题
      queryString = queryString.trim()
      if (!this.isEmpty(queryString)) {
        companyListByName(queryString).then(res => {
          if (res.code === 200) {
            cb(res.data)
          }
        })
      }
    },
    // 标的公司选择后事件
    companyHandleSelect(item) {
      this.loading = true
      var mediationName = this.form.mediationName
      if (mediationName === '' || mediationName === undefined) {
        Notification.error({
          title: this.$t('请先输入公司全称！')
        })
        this.loading = false
        return
      }
      this.resetForm()
      this.tycParam.id = this.form.id
      this.tycParam.tycId = item.id
      this.tycParam.companyName = mediationName
      // 公司类型
      this.tycParam.orgType = item.type
      // 判断机构名称是否存在重复
      this.checkNameExist(mediationName)
      getCompanyByName(this.tycParam).then(res => {
        if (res.code === 200) {
          if (res.msg === 'exist') {
            this.form.mediationName = undefined
            Notification.error({
              title: this.$t('中介机构全称已存在！')
            })
            this.loading = false
          } else if (res.msg === 'nofind') {
            this.form.companyName = undefined
            Notification.error({
              title: this.$t('天眼查没有获取到该中介机构信息！')
            })
            this.loading = false
          } else {
            // 公司简称
            this.form.mediationName = mediationName
            // 企业统一社会信用代码
            this.form.creditCode = res.data.creditCode
            // 法人代表
            this.form.legalPerson = res.data.legalPerson
            // 成立时间
            this.form.establishTime = res.data.setDate
            // 注册地-省
            this.form.provinceRegistered = res.data.provinceRegistered
            this.form.cityRegistered = res.data.cityRegistered

            if (this.$refs?.cityZj?.initCity !== undefined) {
              this.$refs.cityZj.initCity()
              this.$refs.cityZj.initDistrict()
            }
            this.form.districtRegistered = res.data.districtRegistered
            // 注册地-详细地址
            this.form.detailsRegistered = res.data.detailsRegistered
            // 注册资本金额
            this.form.registerCapital = res.data.capitalRegistered
            // 注册资本币种
            this.form.currency = res.data.currency
            // 天眼查ID
            this.form.tycId = res.data.tycId
            // logo
            this.form.logoInfo = res.data.logoInfo
            // 关联公司ID
            this.form.companyId = res.data.id
            this.msgSuccess(this.$t('已获取工商信息！'))
            this.loading = false
          }
        }
      })
    },
    checkNameExist(mediationName) {
      this.$nextTick(() => {
        console.log('checkNameExis1t')
        if (this.isEmpty(mediationName)) {
          this.rules.mediationName = [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
          return
        }
        mediationName = mediationName.trim()
        if (this.isEmpty(mediationName)) {
          this.rules.mediationName = [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
          this.form.mediationName = ''
          return
        }

        getMediationBaseByName({ mediationName: mediationName }).then(res => {
          if (res.data !== null && res.data.id !== this.form.id) {
            this.rules.mediationName = [{ required: true, message: this.$t('机构名称不能重复'), trigger: 'change' }]
            this.form.mediationName = ''
            return
          } else {
            this.rules.mediationName = [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
          }
          this.$forceUpdate()
        })
      })
    },
    // 初始化天眼查获取的数据
    resetForm() {
      this.form.mediationName = undefined
      this.form.creditCode = undefined
      this.form.legalPerson = undefined
      this.form.establishTime = undefined
      this.form.provinceRegistered = undefined
      this.form.cityRegistered = undefined
      this.form.detailsRegistered = undefined
      this.form.registerCapital = undefined
      this.form.districtRegistered = undefined
      this.form.currency = undefined
      this.form.tycId = undefined
      this.form.logoInfo = undefined
      this.form.companyId = undefined
    }
  }
}
</script>
